﻿<?php
class Ecore_Upload_Common {
	public static function process($oFile, $strUploadDir = '', $intMaxSize = IMAGE_SIZE, $arrType = null, $strName = '') {		
		if (!isset( $oFile ) || is_null ( $oFile['tmp_name'] ) || $oFile['name'] == '')
			return array ('error' => 8);
		if (is_null($arrType)) {
			$arrType = array('image/pjpeg', 'image/jpg', 'image/jpeg', 'image/gif', 'image/png');
		}
		
		switch ($oFile ["error"]) {
			case 0 :
				break;
			case 1 :
				return array ('error' => 1);
				break;
			case 2 :
				return array ('error' => 2);
				break;
			case 3 :
				return array ('error' => 3);
				break;
			case 4 :
				return array ('error' => 4);
				break;
			case 5 :
				return array ('error' => 5);
				break;
			case 6 :
				return array ('error' => 6);
				break;
			default :
				return array ('error' => 7);
				break;
		}		
		if (!in_array($oFile['type'], $arrType)) {		
			return array ('error' => 9);
		}
		if ($oFile['size'] <= 0 || $oFile['size'] > $intMaxSize) {
			return array ('error' => 10);
		}
		if( substr($strUploadDir, -1, 1) != '/' ) $strUploadDir .= '/';
		Ecore_Function::mkDirectory($strUploadDir);
		if ($strName != '')
			$strFileName = $strName . strtolower(strrchr($oFile['name'], '.'));
		else
			$strFileName = rand(100, 999) . time() . strtolower(strrchr($oFile['name'], '.'));		
		$strFullPath = $strUploadDir . $strFileName;
		
		move_uploaded_file($oFile['tmp_name'], $strFullPath);
		$arrSize 	= @getimagesize($strFullPath);
		$intWidth 	= 0;
		$intHeight 	= 0;
		if(is_array($arrSize) && count($arrSize)) {
			$intWidth 	=  $arrSize[0];
			$intHeight	=  $arrSize[1];
		}
		return array (
			'error' 	=> 0,
			'name' 		=> $strFileName,
			'fullpath' 	=> $strFullPath,
			'width'  	=> $intWidth,
			'height' 	=> $intHeight
		);		
	}
	public static function thumbImg($strOrigin, $strThumb, $intWidth, $intHeight=0) {
		$objThumb = new Ecore_Thumbnail($strOrigin, $strThumb);
		if ($objThumb->error_msg == '' && $intWidth > 0) {
			$objThumb->quality 		  			= 100;
			$objThumb->output_format 			= 'JPG,JPEG,jpg,jpeg,GIF,gif,PNG,png';
			$objThumb->jpeg_progressive 		= 1;
			$objThumb->bicubic_resample 		= false;
			$objThumb->allow_enlarge			= false;
			if($intHeight > 0) {
				$objThumb->size($intWidth,$intHeight);
			} else {
				$objThumb->size_width($intWidth);
			}
			$objThumb->process();
			$objThumb->save($strThumb);
		}
	}
}